/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.tasks
{
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	
	/**
	 * Task that finishes when certain event is triggered.
	 * 
	 * @example This example will trace only done after the "foo" event is triggered on a certain EventDispatcher  
	 * <listing version="3.0">
	 *  var d:EventDispatcher = new EventDispatcher();
	 * 	tasks.add(
	 * 		new Sequence(
	 *			new WaitForEvent(d, "foo"),
	 * 			new Func(trace, "Done."),
	 * 		)
	 * 	);
	 *  setTimeout(d.dispatchEvent, 1000, new Event("foo"));
	 * </listing>
	 *
	 * @see TaskRunner
	 */
	
	public class WaitForEvent extends Task
	{
		protected var dispatcher:IEventDispatcher;
		protected var event:String;
		
		/**
		 * Create a WaitForEvent task.
		 *
		 * @param dispatcher The element that will dispatch the event
		 * @param event The event name
		 */
		
		public function WaitForEvent(dispatcher:IEventDispatcher, event:String)
		{
			super();
			this.dispatcher = dispatcher;
			this.event = event;
		}
		
		protected function eventDispatched(e:Event):void
		{
			this.taskComplete();
		}
		
		/** @inheritDoc */
		public override function clone():ITask
		{
			return new WaitForEvent(dispatcher, event);
		}

		/**
		 * @inheritDoc
		 */
		public override function start():void
		{
			super.start();
			dispatcher.addEventListener(event,eventDispatched);
		}
		
		/**
		 * @inheritDoc
		 */
		public override function stop():void
		{
			super.stop()
			dispatcher.removeEventListener(event,eventDispatched);
		}
		
	}
}